package de.zainodis.triplog.ui.task;

import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.provider.MediaStore;

import de.zainodis.triplog.data.TripEntry;
import de.zainodis.triplog.util.DateTimeUtils;
import de.zainodis.triplog.util.Utilities;

/**
 * Loads images from the Gallery.
 * Created by fzarrai on 10/2/2014.
 */
public class GalleryLoader extends CursorLoader {

    private long start;
    private long end;

    public final static String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN,
            MediaStore.Images.Media.DATE_ADDED};

    public GalleryLoader(Context context, TripEntry trip) {
        super(context);
        this.start = DateTimeUtils.dbDateStringToDate(trip.getStart()).getTime();
        if (trip.hasEndDate()) {
            this.end = DateTimeUtils.dbDateStringToDate(trip.getEnd()).getTime();
        }
    }

    @Override
    public Cursor loadInBackground() {
        //TODO not filtering correctly for pictures taken on the same date
        //Query for all images from our gallery folder, starting from when the trip started until it ended
        String select = MediaStore.Images.Media.DATA + " like ? and " + MediaStore.Images.Media.DATE_TAKEN + " >= ? ";
        String[] arguments = null;
        if (end > 0) {
            select += "and " + MediaStore.Images.Media.DATE_TAKEN + " <= ?";
            arguments = new String[]{Utilities.APP_DIRECTORY, String.valueOf(start), String.valueOf(end)};
        } else {
            arguments = new String[]{String.format("%%%s%%", Utilities.APP_DIRECTORY), String.valueOf(start)};
        }

        Cursor cursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, select, arguments, null);

        return cursor;
    }
}
